"""
库存相关序列化模式
"""
from marshmallow import Schema, fields, validate, validates, ValidationError
from app.extensions import ma
from app.models.inventory import InventoryType

class InventoryRecordSchema(ma.Schema):
    """库存记录序列化模式"""
    id = fields.Int()
    product_id = fields.Int()
    variant_id = fields.Int()
    type = fields.Str()
    quantity = fields.Int()
    notes = fields.Str()
    created_at = fields.DateTime()
    
    # 附加信息
    product_name = fields.String(dump_only=True)
    variant_specs = fields.Dict(dump_only=True)
    operator_name = fields.String(dump_only=True)

class InventoryInSchema(Schema):
    """入库操作序列化模式"""
    product_id = fields.Integer(required=True)
    variant_id = fields.Integer()
    quantity = fields.Integer(required=True, validate=validate.Range(min=1))
    notes = fields.String()
    
    @validates('quantity')
    def validate_quantity(self, quantity):
        """验证数量"""
        if quantity <= 0:
            raise ValidationError('入库数量必须大于0')

class InventoryOutSchema(Schema):
    """出库操作序列化模式"""
    product_id = fields.Integer(required=True)
    variant_id = fields.Integer()
    quantity = fields.Integer(required=True, validate=validate.Range(min=1))
    notes = fields.String()
    
    @validates('quantity')
    def validate_quantity(self, quantity):
        """验证数量"""
        if quantity <= 0:
            raise ValidationError('出库数量必须大于0')

class InventoryAdjustSchema(Schema):
    """库存调整序列化模式"""
    product_id = fields.Integer(required=True)
    variant_id = fields.Integer()
    quantity = fields.Integer(required=True)  # 可以为正数（增加）或负数（减少）
    notes = fields.String(required=True)  # 调整原因必须说明

class StockQueryResultSchema(Schema):
    """库存查询结果序列化模式"""
    product_id = fields.Integer()
    product_name = fields.String()
    stock = fields.Integer()
    variants = fields.List(fields.Dict())
    
    # 附加统计信息
    total_in = fields.Integer()
    total_out = fields.Integer()
    last_update = fields.DateTime()

class InventorySchema(ma.Schema):
    """库存序列化模式"""
    id = fields.Int()
    product_id = fields.Int()
    variant_id = fields.Int()
    stock = fields.Int()
    created_at = fields.DateTime()
    updated_at = fields.DateTime()

class InventoryRecordSchema(Schema):
    """库存记录数据验证模式"""
    id = fields.Integer(dump_only=True)
    product_id = fields.Integer()
    variant_id = fields.Integer()
    type = fields.String(required=True, validate=validate.OneOf([type.value for type in InventoryType]))
    quantity = fields.Integer(required=True)
    balance = fields.Integer(dump_only=True)
    notes = fields.String(allow_none=True)
    operator_id = fields.Integer(dump_only=True)
    created_at = fields.DateTime(dump_only=True)
    
    @validates('product_id')
    def validate_product_id(self, value):
        """验证商品ID"""
        if not value and not self.context.get('variant_id'):
            raise ValidationError('商品ID和变体ID至少需要一个')
            
        if value:
            from app.models.product import Product
            product = Product.query.get(value)
            if not product:
                raise ValidationError('商品不存在')
    
    @validates('variant_id')
    def validate_variant_id(self, value):
        """验证变体ID"""
        if not value:
            return
            
        from app.models.product import ProductVariant
        variant = ProductVariant.query.get(value)
        if not variant:
            raise ValidationError('商品变体不存在')
            
        # 如果同时提供了商品ID，检查变体是否属于该商品
        product_id = self.context.get('product_id')
        if product_id and variant.product_id != product_id:
            raise ValidationError('商品变体不属于指定商品')
    
    @validates('type')
    def validate_type(self, value):
        """验证类型"""
        if value not in [type.value for type in InventoryType]:
            raise ValidationError('无效的库存操作类型')
    
    @validates('quantity')
    def validate_quantity(self, value):
        """验证数量"""
        # 对于出库和释放操作，检查库存是否足够
        if self.context.get('type') in [InventoryType.OUT.value, InventoryType.RELEASE.value]:
            product_id = self.context.get('product_id')
            variant_id = self.context.get('variant_id')
            
            if variant_id:
                from app.models.product import ProductVariant
                variant = ProductVariant.query.get(variant_id)
                if variant and variant.stock < value:
                    raise ValidationError('商品变体库存不足')
            elif product_id:
                from app.models.product import Product
                product = Product.query.get(product_id)
                if product and product.stock < value:
                    raise ValidationError('商品库存不足') 